package com.fingard.dsp.bank.directbank.cmb04;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.cmb04.util.SDKConfig;
import com.fingard.dsp.bank.directbank.cmb04.util.SDKUtil;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextWriter;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class CMB04Base extends DirectBase implements ITcpClient{
	private static TransIDHelper idHelper = new TransIDHelper(1, 999);

    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.DateTime12Year2Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }
    
	protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }

    protected void writeCommonHeader(XmlTextWriter xmlWriter) {
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
    }
    
    protected String signByRSA(ActSetItem actItem, String signData) {
    	Map<String,String> data_map=new HashMap<String,String>();
		data_map.put(SDKUtil.param_data, signData);
		
		Properties properties = new Properties();
		properties.setProperty("acpsdk.signCert.path", actItem.ownKeyStorePath);
		properties.setProperty("acpsdk.signCert.pwd", actItem.ownKeyPassword);
		properties.setProperty("acpsdk.signCert.type", "PKCS12");
		properties.setProperty("acpsdk.validateCert.path", actItem.oppCertFilePath);
		
		SDKConfig.getConfig().loadPropertiesFromSrc(properties);
	   	SDKUtil.sign(data_map);
	   	WriteBankLogLn("签名结果:" + data_map.get(SDKUtil.param_signature));
	   	return data_map.get(SDKUtil.param_signature);
    }
    
    /**返回数组：[0]ConnState   [1]报文   [2]retCode  [3]retInfo*/
    protected String[] sendToBank(String p_reqStr, CMB04Header p_bankHeader, ActSetItem actItem) throws Exception {
        String[] tmpStrRet = new String[]{"", ""};
        
        String signature = signByRSA(actItem, p_reqStr);
        p_reqStr = p_reqStr + signature;

        // 消息报文头
        StringBuilder tmpReqMsgHead = new StringBuilder();
        tmpReqMsgHead.append("MERX");
        tmpReqMsgHead.append(String.format("%8s", p_reqStr.getBytes(getCharset()).length).replace(' ', '0')); 
        tmpReqMsgHead.append(p_bankHeader.transCode);
        tmpReqMsgHead.append(String.format("%46s",""));
        tmpReqMsgHead.append(Format.Date8Format.format(new Date()));
        tmpReqMsgHead.append(Format.Time6Format.format(new Date()));
        tmpReqMsgHead.append(String.format("%-32s",p_bankHeader.reqSeqID));
        tmpReqMsgHead.append(String.format("%-10s",bankFront.org));
        tmpReqMsgHead.append("010000");
        tmpReqMsgHead.append("CMBMB99");

        // 消息报文
        String tmpReqData = tmpReqMsgHead + p_reqStr;
        WriteBankLogStep2(tmpReqData);

        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.serverPort), this);
        WriteBankLogLn("服务地址：[" + bankFront.serverIP + ":" + bankFront.serverPort + "]。");

        TcpReceiver tmpReceiver = tmpClient.sendMessage(tmpReqData.getBytes(getCharset()));
        tmpStrRet[0] = tmpReceiver.connState;
        if (tmpReceiver.recBytes != null) {
            tmpStrRet[1] = new String(tmpReceiver.recBytes, 0, tmpReceiver.readedLength, getCharset());
            /*if(tmpReceiver.recBytes.length > 93){
            	tmpStrRet[2]= new String(tmpReceiver.recBytes, 87, 6, getCharset());
            }
            if(tmpReceiver.recBytes.length > 193){
            	tmpStrRet[3] = StringHelper.trimStart(new String(tmpReceiver.recBytes, 93, 100, getCharset()).trim(), ":");
            }*/
        } else {
            tmpStrRet[1] = tmpReceiver.getConnMsg();
        }
        tmpStrRet[1] = tmpStrRet[1].replace('\u000E','-');
        WriteBankLogStep3(tmpStrRet[1]);
        if (!tmpReceiver.isCompleted) {
            WriteBankLogLn(tmpReceiver.getConnMsg());
        }

        return tmpStrRet;
    }

    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            if (p_receiver.readedLength >= 4) {
                p_receiver.contentLength = Integer.parseInt(new String(p_receiver.recBytes, 4, 8, getCharset()));
                p_receiver.contentStartIndex = 4;
            }
        }
    }
}
